from django.http import StreamingHttpResponse
from django.http.response import JsonResponse
from django_redis import get_redis_connection
from django.shortcuts import render
import time


def event_stream(request, channel):

    def generator_data():
        redis_client = get_redis_connection()

        pubsub = redis_client.pubsub()
        # 监听频道 21435
        pubsub.subscribe(channel)
        # 持续监听消息、如果 没有发送消息、则阻塞程序
        for message in pubsub.listen():
            if message['type'] == 'message':
                data = message['data'].decode('utf-8')
                for x in data:
                    # sse 返回的数据格式 必须满足 data: <data>\n\n
                    yield f"data: {x}\n\n"
                    time.sleep(0.1)


    response = StreamingHttpResponse(generator_data(), content_type="text/event-stream")
    response['Cache-Control'] = 'no-cache'
    return response


def message(request):
    redis_client = get_redis_connection()
    message = request.POST.get("message")
    channel = request.POST.get("channel")
    redis_client.publish(channel, message)
    return JsonResponse({"status": "ok"})


def sse_index(request):
    return render(request, 'sse.html')

